package com.leemz.ch2.jdbc.util;

import com.leemz.ch2.jdbc.entity.Student;
import com.leemz.ch2.jdbc.inter.IRowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板类，统一处理
 */
public class JdbcTemplate {
    public static<T> T query(String sql, IRowMapper<T> rowMapper, Object... params) {
        //List<Student> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtil.getConnection();
            pstmt = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1, params[i]);
            }
            rs = pstmt.executeQuery();
            return rowMapper.handleResult(rs);
            /*while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                Student student = new Student(name, age);
                student.setId(id);
                list.add(student);
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(rs, pstmt, connection);
        }
        return null;
        //return list;
    }

    public static void update(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        try {
            connection = JdbcUtil.getConnection();
            pstmt = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                pstmt.setObject(i+1, params[i]);
            }
            pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(null, pstmt, connection);
        }
    }
}
